import { ifLoggerKeeper } from "./base";
import { HashMap, Util } from "../lib/Util";
import { http_quest } from "../lib/HttpQuest";
import Debug from "debug"
export type LogKitParams = { url: string, projectid: string }

// 提供一个接入自己的 小小小日志系统的模块
export class LogKitLogger implements ifLoggerKeeper {
    private _catch: HashMap<any> = new HashMap();
    private handle: { stop: any; } | undefined;
    private open: boolean = false;
    private url: string = "";
    private project_id: string = "";
    name = "logkit"
    constructor(cfg: LogKitParams) {
        this.url = cfg.url;
        this.project_id = cfg.projectid
        this.open = true;
    }

    async init() {
        if (this.handle) this.handle.stop();
        this.handle = Util.setInterval(this.update.bind(this), 200);
        return true
    }

    putLogs(data: any) {
        http_quest("post", this.url, data, 0, null, { request_type: "json" }).then(d => {
            // Debug("mx-logger")("success", this.url, d)
            // console.log(d)
        }).catch(e => {
            // Debug("mx-logger")("error", this.url, e)
            // console.error(e)
        })
    }

    private async update() {
        if (!this.open) {
            this._catch.clear();
            return;
        }
        // this.mkdirsSync(this.path);

        let keys = this._catch.keys;
        for (let j = 0; j < keys.length; j++) {
            let cache = this._catch.get(keys[j]);
            let logGroup: { data: any[], action: string } = { data: [], action: keys[j] }
            for (let i = 0; i < cache.length; i++) logGroup.data.push(cache[i]);
            if (logGroup.data.length > 0) {
                // 暂时都投递算了
                this.putLogs(logGroup)
            }
        }

        this._catch.clear();
        return;
    }

    logEvent(uid: string, event_name: string, obj: { [x: string]: string | number }) {
        let s = {
            "project_id": this.project_id,
            "log_category": event_name,             // 记录事件id
            "log_point": obj.type || obj.sType || "null",
            "log_sn": (obj.sActiveId || obj.sActiveID || "null").toString(), // 记录活动id
            "log_data": obj,
            "log_from": (uid || "0").toString(),
        }

        this._catch.add("reports", s);
    }

    logStatic(uid: string, eventType: string, obj: { [x: string]: string | number }) {
        // 暂时没有实现
        // let account_id = (uid || "").toString();
        // let s = {
        //     "#account_id": account_id,
        //     // "#distinct_id": "F53A58ED-E5DA-4F18-B082-7E1228746E88",
        //     "#type": (eventType || "").toString(),
        //     // "#ip": "192.168.171.111",
        //     "#time": /*"2017-12-18 14:37:28.527"*/ LocalDate.formateString(Date.now()),
        //     "properties": obj
        // }

        // this._catch.add('_static_', s);
    }

    logApi(api: string, method: string, uid: string, succ: boolean, consumeTime: number, reqID: string, param: string, response: string) {
        let s = {
            'project_id': this.project_id,
            'api_category': api,
            'api_method': method,
            'is_success': succ ? 1 : 0, // 1成功 0失败
            'consume_time': consumeTime, // 耗时 15毫秒
            'user_from': (uid || "null").toString(),
            'user_identify': (reqID || "null").toString(), // 记录标识  可以是订单号
            'api_response': response.slice(0, 300), // 只显示前100个字符试试
            'api_param': param.slice(0, 300), // 只显示前100个字符试试
        }

        this._catch.add('apis', s);
    }
}